{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在上一次最后留给思考：给定三条线段的长度，判断是否能组成三角形，如果能输出三角形：普通三角形、等腰三角形、等边三角形或直角三角形。不知道大家有没有写出求解程序，如果没有写出来也没有关系，今天会给出一种解决方案。如果大家去写了就会发现，我们在求解三角形类型的时候，每次需要判断新给定的三条边时，都需要重复输入一遍求解代码，这样就会出现很多代码的重复输入，有没有什么办法能让我们不必重复输入相同逻辑代码呢？这个是肯定有的，其中一种解决方案就是今天讲解的 **函数**。在介绍函数之前，先来整体了解一下为什么需要使用函数？\n",
    "\n",
    "1. 就像上面介绍的：最大化代码重用，最小化代码冗余。冗余就是指代码重复\n",
    "2. 程序分解。在代码量越来越大后，就需要我们将大的程序进行分解，且有效的组织代码结构，函数就是分解和组织代码的最基础手段之一。\n",
    "\n",
    "# 函数定义\n",
    "\n",
    "```\n",
    "def fun_name(arg1, arg2,... argN):\n",
    "    statements\n",
    "```\n",
    "\n",
    "函数常常包含有返回值，这个时候函数至少包含一个 `return`语句。包含有返回语句的函数\n",
    "\n",
    "```\n",
    "def fun_name(arg1, arg2,... argN):\n",
    "    ...\n",
    "    return value\n",
    "```\n",
    "\n",
    "简单的规则：\n",
    "\n",
    "* 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。\n",
    "* 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。\n",
    "* 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。\n",
    "* 函数内容以冒号起始，并且缩进。\n",
    "* return [表达式] 结束函数，选择性地返回一个值给调用方。不带表达式的return相当于返回 None。\n",
    "\n",
    "下面是一个输出 “你好” 的函数定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hello():\n",
    "    print(\"你好！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再看一个复杂点的函数定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 打印一个加法口诀表\n",
    "def tab(x):\n",
    "    for i in range(x+1):\n",
    "        for j in range(1, i+1):\n",
    "            print('%d+%d=%d' %(j,i,i+j), end='\\t')\n",
    "        print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数调用\n",
    "\n",
    "函数定义完成后，使用如下格式调用\n",
    "\n",
    "* 无参数函数调用：func_name()\n",
    "* 有参数函数调用：func_name(arg1,arg2,...)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好！\n"
     ]
    }
   ],
   "source": [
    "hello()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "1+1=2\t\n",
      "1+2=3\t2+2=4\t\n",
      "1+3=4\t2+3=5\t3+3=6\t\n",
      "1+4=5\t2+4=6\t3+4=7\t4+4=8\t\n",
      "1+5=6\t2+5=7\t3+5=8\t4+5=9\t5+5=10\t\n",
      "1+6=7\t2+6=8\t3+6=9\t4+6=10\t5+6=11\t6+6=12\t\n",
      "1+7=8\t2+7=9\t3+7=10\t4+7=11\t5+7=12\t6+7=13\t7+7=14\t\n",
      "1+8=9\t2+8=10\t3+8=11\t4+8=12\t5+8=13\t6+8=14\t7+8=15\t8+8=16\t\n",
      "1+9=10\t2+9=11\t3+9=12\t4+9=13\t5+9=14\t6+9=15\t7+9=16\t8+9=17\t9+9=18\t\n"
     ]
    }
   ],
   "source": [
    "tab(9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "1+1=2\t\n",
      "1+2=3\t2+2=4\t\n",
      "1+3=4\t2+3=5\t3+3=6\t\n",
      "1+4=5\t2+4=6\t3+4=7\t4+4=8\t\n",
      "1+5=6\t2+5=7\t3+5=8\t4+5=9\t5+5=10\t\n",
      "1+6=7\t2+6=8\t3+6=9\t4+6=10\t5+6=11\t6+6=12\t\n",
      "1+7=8\t2+7=9\t3+7=10\t4+7=11\t5+7=12\t6+7=13\t7+7=14\t\n"
     ]
    }
   ],
   "source": [
    "tab(7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再看一个有返回值的函数定义和调用。求两个数的和。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "直接使用调用结果： 7\n",
      "保存使用调用结果： 7\n"
     ]
    }
   ],
   "source": [
    "# 定义 add 函数，并返回 2 个数的和\n",
    "def add(x,y):\n",
    "    return x+y\n",
    "\n",
    "# 调用 add 函数\n",
    "print(\"直接使用调用结果：\", add(3,4))\n",
    "\n",
    "# 保存函数调用结果\n",
    "result = add(5,6)\n",
    "print(\"保存使用调用结果：\", add(3,4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数参数\n",
    "\n",
    "由于 python 动态类型域名，在使用到变量的时候才会动态计算类型，\n",
    "每一个函数都有自己处理和使用参数的方式，这也决定了调用时传入的参数必须符合函数处理时对变量使用的规范。\n",
    "所以在函数调用的时候需要注意，传入的参数类型。\n",
    "\n",
    "比如上线定义的 `add` 函数，虽然本意是计算两个数的和。但是它的实际语义是：将 `+` 运算符作用到变量 x 引用的对象和变量 y 引用的对象上，所以只要 x 引用对象和 y 引用对象符合 `+` 运算符定义，都可以正常调用 `add` 函数。比如下面的调用："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "aab\n",
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "print(add('aa', 'b'))\n",
    "print(add([1,2],[3,4,5]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是下面的调用将会出现错误，因为 `+` 运算符不能同时应用到 2 个不同类型的对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "must be str, not int",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-34-7f8ab9385845>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'aa'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-23-a620d74bd031>\u001b[0m in \u001b[0;36madd\u001b[0;34m(x, y)\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# 定义 add 函数，并返回 2 个数的和\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m     \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;31m# 调用 add 函数\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mTypeError\u001b[0m: must be str, not int"
     ]
    }
   ],
   "source": [
    "# error\n",
    "add('aa',4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参数传递\n",
    "\n",
    "python 中一切数据都是对象。在定义时定义的参数只是一个变量，在函数调用时传入的参数才是对象，并将响应的参数变量引用到传入的对象。\n",
    "比如上面的 `add` 方法定义和调用，在定义时定义了 x 和 y 两个参数变量，调用 `add(3,4)` 时，传入了 3 和 4 两个对象，这时变量 x 引用到 3 这个对象，变量 y 引用到 4 这个对象。请看下面的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x 参数传入:\n",
      "     True\n",
      "     139675229648744 139675229648744\n",
      "     True\n",
      "y 参数传入:\n",
      "     True\n",
      "     139675167007112 139675167007112\n",
      "     True\n",
      "=================\n",
      "x 参数传入:\n",
      "     True\n",
      "     139675395447968 139675395447968\n",
      "     True\n",
      "y 参数传入:\n",
      "     True\n",
      "     139675166995008 139675166995008\n",
      "     True\n"
     ]
    }
   ],
   "source": [
    "a=\"99\"\n",
    "b=[1,2,3]\n",
    "def f(x, y):\n",
    "    print(\"x 参数传入:\")\n",
    "    print(\"    \", x==a)\n",
    "    print(\"    \", id(x), id(a)) # 返回对象的唯一标识符\n",
    "    print(\"    \", x is a)\n",
    "    print(\"y 参数传入:\")\n",
    "    print(\"    \", y==b)\n",
    "    print(\"    \", id(y), id(b)) # 返回对象的唯一标识符\n",
    "    print(\"    \", y is b)\n",
    "\n",
    "f(a,b)\n",
    "print(\"=================\")\n",
    "a=1\n",
    "b=(1,2,2)\n",
    "f(a,b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从上面的实例可以看到不论传入的何种参数类型（简单对象或复杂对象、可变对象或不可变对象），函数的参数变量引用的对象都是原始对象，这里和其他语言里面种传值调用和传引用调用是不一样的。此时变量 a 和 参数变量 x 引用的是同一个对象，变量 b 和参数变量 y引用的同一个对象，所以在参数里面对 x 或 y 进行修改会影响 a 或 b 的访问结果；但是对 a 和 b 进行赋值不会影响 a 或 b 的访问结果，因为赋值只是将 a 或 b 引用到新的对象，并没有改变原有对象。请看下面例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a= [1]  b= [1]\n",
      "x= [1, [1, 2]]  y= [1, 1, 2]\n",
      "a= [1, [1, 2]]  b= [1]\n"
     ]
    }
   ],
   "source": [
    "a = [1]\n",
    "b = [1]\n",
    "print(\"a=\",a,\" b=\",b)\n",
    "def change(x,y):\n",
    "    x.append([1,2])\n",
    "    y = y+[1,2]\n",
    "    print(\"x=\",x,\" y=\",y)\n",
    "\n",
    "    \n",
    "change(a,b)\n",
    "print(\"a=\",a,\" b=\",b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "参数修改影响传入对象，只发生在 **可变对象** 上，因为试着修改不可变对象将会报错，\n",
    "所以对于传入不可变对象只能对参数变量做赋值或取值操作，不能修改操作。\n",
    "\n",
    "见下面例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'tuple' object has no attribute 'append'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-17-25239a894afa>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mchange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-14-f7db784409a1>\u001b[0m in \u001b[0;36mchange\u001b[0;34m(x, y)\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"a=\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\" b=\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mchange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m     \u001b[0mx\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      6\u001b[0m     \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      7\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"x=\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\" y=\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'"
     ]
    }
   ],
   "source": [
    "a = (1,1)\n",
    "b = [1]\n",
    "change(a,b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参数\n",
    "\n",
    "调用函数时可使用的正式参数类型：\n",
    "\n",
    "* 必需参数\n",
    "* 关键字参数\n",
    "* 默认参数\n",
    "* 不定长参数\n",
    "* 命名参数\n",
    "* 不定长命名参数\n",
    "\n",
    "他们的区别主要主要体现在 *声明方式、调用解析* 的不同。\n",
    "\n",
    "### 必需参数\n",
    "\n",
    "必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。\n",
    "\n",
    "* 声明方式：正常的参数变量\n",
    "* 调用解析：严格位置前后顺序解析\n",
    "\n",
    "比如上面的 `change` 函数的参数都是必要参数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x= [1, [1, 2]]  y= [2, 1, 2]\n",
      "a= [1, [1, 2]]  b= [2]\n"
     ]
    }
   ],
   "source": [
    "def change(x,y):\n",
    "    x.append([1,2])\n",
    "    y = y+[1,2]\n",
    "    print(\"x=\",x,\" y=\",y)\n",
    "\n",
    "    \n",
    "a = [1]\n",
    "b = [2]\n",
    "change(a,b)\n",
    "print(\"a=\",a,\" b=\",b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 关键字参数\n",
    "\n",
    "关键字参数和函数调用关系紧密，函数调用使用关键字参数来确定传入的参数值。\n",
    "\n",
    "* 声明方式：正常的参数变量，和必需参数相同\n",
    "* 调用解析：在调用是具体指定传入的参数变量，不受前后顺序限制，关键字必须是声明的参数变量\n",
    "\n",
    "由于声明方式和必须参数相同，还是以上面的 `change` 函数为例（不需重新声明）看调用方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x= [2, [1, 2]]  y= [1, 1, 2]\n",
      "a= [1]  b= [2, [1, 2]]\n"
     ]
    }
   ],
   "source": [
    "a = [1]\n",
    "b = [2]\n",
    "change(y=a,x=b)        # 指定传入特定的参数变量关键字\n",
    "print(\"a=\",a,\" b=\",b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 默认参数\n",
    "\n",
    "在函数定义声明参数时，可以给参数一个默认值，在函数调用时如果没有传入这个参数，就会使用默认值。\n",
    "\n",
    "* 声明方式：正常的参数变量，在声明是赋值一个默认值。默认参数的声明一定要在必要参数之后。\n",
    "* 调用解析：没有传入时解析到默认值，传入参数时解析到传入值。传入值调用方式可以是 必要参数 或 关键字参数 形式\n",
    "\n",
    "> 注意：不是默认参数，在调用时必须参数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正常参数调用： 3\n",
      "默认参数调用： 5\n"
     ]
    }
   ],
   "source": [
    "def add(a,b=2):\n",
    "    return a+b\n",
    "\n",
    "print(\"正常参数调用：\",add(1))\n",
    "print(\"默认参数调用：\",add(1,4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下声明方式是错误的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (<ipython-input-33-70d1e75f5033>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-33-70d1e75f5033>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    def add(a=1,b):\u001b[0m\n\u001b[0m           ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "def add(a=1,b):\n",
    "    return a+b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 不定长参数\n",
    "\n",
    "上面 `add` 实现了求 2 个数的和，如果我们需要同时求多个数的和呢？\n",
    "并且数的数量还不是确定的，总不能每次调用都修改一遍函数定义吧！\n",
    "这个时候就需要使用不定长参数。\n",
    "\n",
    "不定长参数接受在函数调用时传入任意多个参数。\n",
    "\n",
    "* 声明方式：前面带有 `*` 的参数就是不定长参数。不定长参数的声明一定要在必要参数或默认参数之后。\n",
    "* 调用解析：没有传入时解析到默认值，传入参数时解析到传入值。传入值调用方式可以是 必要参数 或 关键字参数 形式\n",
    "\n",
    "> 注意：\n",
    "> \n",
    "> * 一个函数里面只能有一个不定长参数\n",
    "> * 不定长参数类型是 `tuple`，就意味着不定长参数本身是不可改变的，但是传入的可变数据是可以改变的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[other] 参数类型: <class 'tuple'> ()\n",
      "3\n",
      "[other] 参数类型: <class 'tuple'> ()\n",
      "3\n",
      "[other] 参数类型: <class 'tuple'> (3, 4)\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "def add(a,b=2, *other):\n",
    "    print(\"[other] 参数类型:\", type(other),other)\n",
    "    return a+b+sum(other)\n",
    "\n",
    "print(add(1))\n",
    "print(add(1,2))\n",
    "print(add(1,2,3,4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 命名参数\n",
    "\n",
    "在不定长参数后面声明的参数就是命名参数。命名参数的调用必须使用关键字参数的调用方式调用。\n",
    "\n",
    "* 声明方式：参数名字和必须参数一样，只是位置在不定参数之后\n",
    "* 调用解析：调用时必须使用使用关键字参数调用方式\n",
    "\n",
    "> 注意：\n",
    "> * 命名参数尽量为其声明默认值\n",
    "> * 不定长参数的名字可以省略，只保留 `*`。这个时候只是表示后面的参数是命名参数，不再接受不定长参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[other] 参数类型: <class 'tuple'> (3, 4)\n",
      "15\n"
     ]
    }
   ],
   "source": [
    "def add(a,b=2, *other, c):\n",
    "    print(\"[other] 参数类型:\", type(other),other)\n",
    "    return a+b+sum(other)+c\n",
    "\n",
    "print(add(1,2,3,4,c=5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当不接受不定长参数的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "def add_3(a,b=2, *, c):\n",
    "    return a+b+c\n",
    "\n",
    "print(add_3(1,2, c=3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是下面的调用时错误的，因为参数个数不匹配"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "add_3() takes from 1 to 2 positional arguments but 4 positional arguments (and 1 keyword-only argument) were given",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-61-5b2ac4a65da2>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0madd_3\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: add_3() takes from 1 to 2 positional arguments but 4 positional arguments (and 1 keyword-only argument) were given"
     ]
    }
   ],
   "source": [
    "print(add_3(1,2,3,4,c=5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 不定长命名参数\n",
    "\n",
    "在函数调用时接受传入任意多个命名参数。\n",
    "\n",
    "* 声明方式：前面带有 ** 的参数。不定长参数的声明一定要在必要参数、默认参数或命名参数之后。\n",
    "* 调用解析：以关键字参数形式调用，对于不能匹配的的必要参数或关键字参数，都将放入这个参数中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "named p: {'b': 2, 'c': 3}\n",
      "1\n",
      "named p: {'b': 2, 'c': 3}\n"
     ]
    }
   ],
   "source": [
    "def named_p(a=1, **args):\n",
    "    print(a)\n",
    "    print(\"named p:\", args)\n",
    "    \n",
    "named_p(1,b=2,c=3)\n",
    "named_p(a=1,b=2,c=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下调用会出现错误"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "positional argument follows keyword argument (<ipython-input-209-5ace63a7163f>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-209-5ace63a7163f>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    named_p(a=1,3,4)\u001b[0m\n\u001b[0m               ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m positional argument follows keyword argument\n"
     ]
    }
   ],
   "source": [
    "named_p(a=1,3,4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在针对上片的练习可以使用函数实现了：判断三角形形状"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 223,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "不能组成三角形\n",
      "等腰三角形\n",
      "等边三角形\n",
      "直角三角形\n"
     ]
    }
   ],
   "source": [
    "def shape(a,b,c):\n",
    "    \"\"\"\n",
    "    判断三角形形状\n",
    "    a、b、c 给定三角形三条边长度\n",
    "    \"\"\"\n",
    "    ms,md,mx = sorted([a,b,c])\n",
    "    \n",
    "    if ms <= mx-md:\n",
    "        print(\"不能组成三角形\")\n",
    "    elif ms==md and md==mx:\n",
    "        print(\"等边三角形\")\n",
    "    elif ms==md or md==mx:\n",
    "        if ms**2 + md**2 == mx**2:\n",
    "            print(\"等腰直角三角形\")\n",
    "        else:\n",
    "            print(\"等腰三角形\")\n",
    "    elif ms**2 + md**2 == mx**2:\n",
    "        print(\"直角三角形\")\n",
    "    else:\n",
    "        print(\"普通三角形\")\n",
    "    return\n",
    "\n",
    "shape(1,3,2)\n",
    "shape(1,2,2)\n",
    "shape(3,3,3)\n",
    "shape(3,4,5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数注解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def func1(a,b,c):\n",
    "    return a+b+c\n",
    "\n",
    "func1(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def func2(a:'spam', b:(1,10), c:float)->int:\n",
    "    return a+b+c\n",
    "    \n",
    "func2(1,2,3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 'spam', 'b': (1, 10), 'c': float, 'return': int}"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "func2.__annotations__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "15"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def func2(a:'spam'=4, b:(1,10)=5, c:float=6)->int:\n",
    "    return a+b+c\n",
    "func2()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 匿名函数：lambda \n",
    "\n",
    "python 使用 lambda 来创建匿名函数。\n",
    "\n",
    "所谓匿名，意即不再使用 def 语句这样标准的形式定义一个函数。\n",
    "\n",
    "* lambda 只是一个表达式，函数体比 def 简单很多。\n",
    "* lambda的主体是一个表达式，而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。\n",
    "* lambda 函数拥有自己的命名空间，且不能访问自己参数列表之外或全局命名空间里的参数。\n",
    "* 虽然lambda函数看起来只能写一行，却不等同于C或C++的内联函数，后者的目的是调用小函数时不占用栈内存从而增加运行效率。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "相加后的值为 :  30\n",
      "相加后的值为 :  40\n"
     ]
    }
   ],
   "source": [
    "# 可写函数说明\n",
    "sum = lambda a, b: a + b\n",
    " \n",
    "# 调用sum函数\n",
    "print (\"相加后的值为 : \", sum( 10, 20 ))\n",
    "print (\"相加后的值为 : \", sum( 20, 20 ))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 变量作用域\n",
    "\n",
    "Python 中，程序的变量并不是在哪个位置都可以访问的，访问权限决定于这个变量是在哪里赋值的。\n",
    "\n",
    "变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种，分别是：\n",
    "\n",
    "* L （Local） 局部作用域\n",
    "* E （Enclosing） 闭包函数外的函数中\n",
    "* G （Global） 全局作用域\n",
    "* B （Built-in） 内建作用域\n",
    "\n",
    "以 L –> E –> G –>B 的规则查找，即：在局部找不到，便会去局部外的局部找（例如闭包），再找不到就会去全局找，再者去内建中找。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = int(2.9)  # 内建作用域\n",
    " \n",
    "g_count = 0  # 全局作用域\n",
    "def outer():\n",
    "    o_count = 1  # 闭包函数外的函数中\n",
    "    def inner():\n",
    "        i_count = 2  # 局部作用域"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，其它的代码块（如 if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这些语句内定义的变量，外部也可以访问，如下代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "可以访问 a： 1\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'inner_a' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-76-212c676a7b89>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      7\u001b[0m     \u001b[0minner_a\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0mscope1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minner_a\u001b[0m\u001b[0;34m)\u001b[0m   \u001b[0;31m# inner_a 在这里不可访问\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'inner_a' is not defined"
     ]
    }
   ],
   "source": [
    "if True:\n",
    "    a = 1\n",
    "\n",
    "print(\"可以访问 a：\", a)\n",
    "\n",
    "def scope1():\n",
    "    inner_a = 2\n",
    "scope1()\n",
    "print(inner_a)   # inner_a 在这里不可访问"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## global 和 nonlocal关键字\n",
    "\n",
    "** 全局变量和局部变量 **\n",
    "\n",
    "定义在函数内部的变量拥有一个局部作用域，定义在函数外的拥有全局作用域。\n",
    "\n",
    "局部变量只能在其被声明的函数内部访问，而全局变量可以在整个程序范围内访问。调用函数时，所有在函数内声明的变量名称都将被加入到作用域中。如下实例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数内是局部变量 :  30\n",
      "函数外是全局变量 :  0\n"
     ]
    }
   ],
   "source": [
    "total = 0 # 这是一个全局变量\n",
    "\n",
    "# 可写函数说明\n",
    "def sum( arg1, arg2 ):\n",
    "    #返回2个参数的和.\"\n",
    "    total = arg1 + arg2 # total在这里是局部变量.\n",
    "    print (\"函数内是局部变量 : \", total)\n",
    "    return total\n",
    " \n",
    "#调用sum函数\n",
    "sum( 10, 20 )\n",
    "print (\"函数外是全局变量 : \", total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当内部作用域想修改外部作用域的变量时，就要用到global和nonlocal关键字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "函数内是局部变量 :  30\n",
      "函数外是全局变量 :  30\n"
     ]
    }
   ],
   "source": [
    "total = 0 # 这是一个全局变量\n",
    "\n",
    "# 可写函数说明\n",
    "def sum2( arg1, arg2 ):\n",
    "    #返回2个参数的和.\"\n",
    "    global total\n",
    "    total = arg1 + arg2 # total在这里是局部变量.\n",
    "    print (\"函数内是局部变量 : \", total)\n",
    "    return total\n",
    " \n",
    "#调用sum函数\n",
    "sum2( 10, 20 )\n",
    "print (\"函数外是全局变量 : \", total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果要修改嵌套作用域（enclosing 作用域，外层非全局作用域）中的变量则需要 nonlocal 关键字了，如下实例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100\n",
      "100\n"
     ]
    }
   ],
   "source": [
    "def outer():\n",
    "    num = 10\n",
    "    def inner():\n",
    "        nonlocal num   # nonlocal关键字声明\n",
    "        num = 100\n",
    "        print(num)\n",
    "    inner()\n",
    "    print(num)\n",
    "outer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下函数执行将产生错误，因为 a 是一个局部变量，但是在使用时候并没有定义。有 2 中修改方式：\n",
    "\n",
    "1. 将 `=` 左边的变量 `a` 换成其他变量名称（比如 `b`）。\n",
    "2. 将外部 `a` 作为参数传入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "ename": "UnboundLocalError",
     "evalue": "local variable 'a' referenced before assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mUnboundLocalError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-91-4212688e84b0>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      3\u001b[0m     \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mtest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-91-4212688e84b0>\u001b[0m in \u001b[0;36mtest\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m10\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mtest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m     \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0mtest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'a' referenced before assignment"
     ]
    }
   ],
   "source": [
    "a = 10\n",
    "def test():\n",
    "    a = a + 1\n",
    "    print(a)\n",
    "test()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用以下方式查看内建作用域中的变量。\n",
    "\n",
    "```\n",
    "dir(__builtin__) # 或 dir(__builtins__)\n",
    "```\n",
    "\n",
    "这里 `__builtin__` 和 `__builtins__` 是有区别的，并且在主模块和子模块中有所不同。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 工厂函数：闭包\n",
    "\n",
    "在函数作用域中，有一个闭包作用域，那怎么产生闭包呢！只要在函数内部定义函数，就会产生闭包作用域。\n",
    "\n",
    "闭包作用域：外部函数的本地作用域就是闭包函数的闭包作用域。\n",
    "\n",
    "工厂函数：一个返回值时函数的函数就是，这里的返回值函数也叫闭包函数或内部函数，工厂函数也叫外部函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [],
   "source": [
    "def marker(n):\n",
    "    def action(x):\n",
    "        return x ** n\n",
    "    return action"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.marker.<locals>.action(x)>"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = marker(2)\n",
    "f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9 16\n"
     ]
    }
   ],
   "source": [
    "print(f(3), f(4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "16"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "64\n",
      "16\n"
     ]
    }
   ],
   "source": [
    "g = marker(3)\n",
    "print(g(4))             # 4 ** 3\n",
    "print(f(4))             # 4 ** 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于简单的函数逻辑，也可指直接返回 lambda 函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "def marker(n):\n",
    "    return lambda x: x**n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "64"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "h = marker(3)\n",
    "h(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "** 闭包使用建议 **\n",
    "\n",
    "闭包在必须的时候才使用，可以使用类进行替换。类后面会详细介绍。\n",
    "注意闭包和循环共同使用时，变量的作用域"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数对象\n",
    "\n",
    "python 秉承着一切皆对象的理念，函数也是一个对象，具有属性（可以使用dir()查询）。作为对象，它还可以赋值给其它对象名，或者作为参数传递。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fun_obj1(f, a):\n",
    "    f(a)\n",
    "\n",
    "def fun_obj2(v):\n",
    "    print(v*2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "fun_obj1(fun_obj2, 3) # 函数对象作为参数\n",
    "obj1 = fun_obj1       # 函数对象赋值\n",
    "obj1(fun_obj2, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以直接使用匿名函数调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n"
     ]
    }
   ],
   "source": [
    "fun_obj1(lambda v: print(v ** 2), 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成函数: yield vs. return\n",
    "\n",
    "在函数返回值的时候我们使用 `return`，还有一种方式是使用 `yield` 关键字，此时叫做 **生成函数**。有以下特点：\n",
    "\n",
    "* 含有yield关键字\n",
    "* 调用生成器函数会返回一个生成器\n",
    "* 调用生成器函数时, 它包含的代码并不会马上执行, 而是等到访问生成器元素时才一段一段地执行.\n",
    "\n",
    "使用场景：当有大量的数据访问，并且每个数据只访问一次，使用生成器会节省大量空间\n",
    "\n",
    "对于普通的生成器，第一个next调用，相当于启动生成器，会从生成器函数的第一行代码开始执行，直到第一次执行完yield语句（第4行）后，跳出生成器函数。\n",
    "\n",
    "然后第二个next调用，进入生成器函数后，从yield语句的下一句语句（第5行）开始执行，然后重新运行到yield语句，执行后，跳出生成器函数，\n",
    "\n",
    "后面再次调用next，依次类推。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 168,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在函数调用时不会马上执行代码，返回生成器\n",
      "<generator object gen_func at 0x7f08a824ef10>\n",
      "在访问生成器的时候，才会一段一段执行代码\n",
      "yield 1...\n",
      "get 1: 1\n",
      "yield 2...\n",
      "get 2: 2\n",
      "yield 3...\n",
      "get 3: 3\n",
      "如果已经超出生成器范围，会产生一个错误；但是如果函数里面最后生成器后面还有代码，会先执行\n",
      "yield 4... 是不是外面调用报错了...\n"
     ]
    },
    {
     "ename": "StopIteration",
     "evalue": "5",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mStopIteration\u001b[0m                             Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-168-10c15cc024b5>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     17\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"get 3:\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgen_res\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     18\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"如果已经超出生成器范围，会产生一个错误；但是如果函数里面最后生成器后面还有代码，会先执行\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 19\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"get 4:\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgen_res\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mStopIteration\u001b[0m: 5"
     ]
    }
   ],
   "source": [
    "def gen_func():\n",
    "    print ('yield 1...')\n",
    "    yield 1\n",
    "    print ('yield 2...')\n",
    "    yield 2\n",
    "    print ('yield 3...')\n",
    "    yield 3\n",
    "    print ('yield 4... 是不是外面调用报错了...')\n",
    "    return 5\n",
    "\n",
    "gen_res = gen_func()\n",
    "print(\"在函数调用时不会马上执行代码，返回生成器\")\n",
    "print(gen_res)\n",
    "print(\"在访问生成器的时候，才会一段一段执行代码\")\n",
    "print(\"get 1:\", next(gen_res))\n",
    "print(\"get 2:\", next(gen_res))\n",
    "print(\"get 3:\", next(gen_res))\n",
    "print(\"如果已经超出生成器范围，会产生一个错误；但是如果函数里面最后生成器后面还有代码，会先执行\")\n",
    "print(\"get 4:\", next(gen_res))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## send vs. next\n",
    "\n",
    "send 和 next 功能相识，区别是send()可以传递yield表达式的值进去，而next()不能传递特定的值，只能传递None进去。因此，我们可以看做c.next() 和 c.send(None) 作用是一样的。需要提醒的是，第一次调用时，请使用next()语句或是send(None)，不能使用send发送一个非None的值，否则会出错的，因为没有Python yield语句来接收这个值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "get None\n",
      "40\n",
      "get None\n",
      "60\n",
      "get None\n"
     ]
    }
   ],
   "source": [
    "def double_inputs():\n",
    "    while True:\n",
    "        x = yield\n",
    "        if not x:\n",
    "            return\n",
    "        print(x * 2)\n",
    "        yield x*2\n",
    "\n",
    "gen = double_inputs()\n",
    "gen.send(None)\n",
    "\n",
    "gen.send(10)\n",
    "print(\"get\", next(gen))\n",
    "gen.send(20)\n",
    "print(\"get\", gen.send(None))\n",
    "gen.send(30)\n",
    "print(\"get\", next(gen))\n",
    "\n",
    "gen.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成器表达式\n",
    "\n",
    "在之前介绍 *列表推导（解析表达式）* 的时候，已经见过生成器表达式的形式了，有了上面的生产函数的知识，理解生成器表达式就简单了。\n",
    "\n",
    "生成器表达式与列表推导在语法上十分相似:\n",
    "\n",
    "* 列表推导（解析表达式）使用[]: [i for i in arr]\n",
    "* 生成器表达式使用(): (i for i in arr)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<generator object <genexpr> at 0x7f08a82e6468>"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = (x**2 for x in range(4))\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1, 4)"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(s),next(s),next(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "generator"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1, 4)"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a,b,c=(x**2 for x in range(3))\n",
    "\n",
    "a,b,c"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数递归\n",
    "\n",
    "有一类函数在使用的时候需要注意一下，就是在函数内部调用自己的函数，称为 **递归函数**。先看一个例子：\n",
    "\n",
    "求 1~n 之间所有整数的乘积？\n",
    "\n",
    "先来看循环的方式实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "def sum_n(n):\n",
    "    result = 1\n",
    "    while n>1:\n",
    "        result *= n\n",
    "        n -= 1\n",
    "    return result\n",
    "\n",
    "print(sum_n(5))\n",
    "print(sum_n(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们也可以使用递归实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 203,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "def sum_n2(n):\n",
    "    if(n==1): return 1\n",
    "    return n * sum_n2(n-1)\n",
    "\n",
    "\n",
    "print(sum_n2(5))\n",
    "print(sum_n2(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们看到在使用递归的时候，我们不会展开具体的实现过程，只是根据乘积递归定义 `n! = n * (n-1)!` 用程序表达出来，在执行的时候会自动调用展开。\n",
    "再看一个例子：\n",
    "\n",
    "求第 n 个斐波拉契数？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 208,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 1 2 3 5 8\n"
     ]
    }
   ],
   "source": [
    "def f(n):\n",
    "    if n==1 or n==2: return 1\n",
    "    return f(n-1) + f(n-2)\n",
    "\n",
    "print(f(1),f(2),f(3),f(4),f(5),f(6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用递归函数注意： **递归函数必须有一个终止条件，不然就是循环了**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 函数式编程工具\n",
    "\n",
    "在 python 中提供了一些列和函数式编程的工具和方法，这里将常用列举出来大家有兴趣可以学习使用。\n",
    "\n",
    "1. map、filter、reduce、zip\n",
    "2. operator、functools 包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 程序设计原则\n",
    "\n",
    "1. 最小化变量作用于\n",
    "2. 最小化跨文件改变\n",
    "3. 使用 lambda 表达式时，尽量保持逻辑简单，复杂逻辑使用函数、类或其他方式\n",
    "4. 对于很多数据处理，尽量使用生成函数\n",
    "5. 慎用闭包"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
